package com.llb666.e.shop.infracore.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

/**
 * 跨域配置.
 * C - Cross  O - Origin  R - Resource  S - Sharing.
 *
 * @author llb666
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        //支持Cookie跨域
        config.setAllowCredentials(true);
        /*
         * 设置允许的请求链接
         *
         * config.setAllowedOrigins(Collections.singletonList("http://localhost:8080"));
         *
         * config.addAllowedOrigin("*"); // 允许所有
         */
        config.addAllowedOriginPattern("*");
        //设置允许的header
        config.setAllowedHeaders(Collections.singletonList("*"));
        //设置允许请求的方式
        config.setAllowedMethods(Collections.singletonList("*"));

        config.setMaxAge(300L);
        //为url添加映射路径
        source.registerCorsConfiguration("/**", config);
        // 返回重新定义好的corsSource
        return new CorsFilter(source);
    }
}
